package com.evoupsight.monitorpass.alarm.util;

import com.evoupsight.monitorpass.alarm.exporession.MainVisitor;
import com.evoupsight.monitorpass.alarm.exporession.TriggerLexer;
import com.evoupsight.monitorpass.alarm.exporession.TriggerParser;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author evoup
 */
@SuppressWarnings("Duplicates")
public class ExpressionUtil {
    private static final Logger LOG = LoggerFactory.getLogger(ExpressionUtil.class);

    /**
     * 通过antlr判断逻辑真假
     *
     * @param expression
     * @return
     */
    public static Boolean antlrTrueFalse(String expression) {
        try {
            CharStream input = new ANTLRInputStream(expression);
            TriggerLexer lexer = new TriggerLexer(input);
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            TriggerParser parser = new TriggerParser(tokens);
            ParseTree tree = parser.expr();
            MainVisitor.Visitor eval = new MainVisitor.Visitor();
            Object visit = eval.visit(tree);
            LOG.info("Trigger result:" + visit);
            System.out.println("check done");
            return Boolean.valueOf(visit.toString());
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return false;
        }

    }
}
